package 双端队列.数组实现;

import java.util.Iterator;

public class ArrayDeque<E> implements Iterable<E> {
    E[] array;
    int head;
    int tail;
    int capacity;

    @SuppressWarnings("all")
    public ArrayDeque(int capacity) {
        this.capacity = capacity + 1;
        array = (E[]) new Object[capacity + 1];
    }

    public boolean offerFirst(E e) {
        if (isFull()) {
            return false;
        }
        array[head] = e;
        head = (head + 1) % capacity;
        return true;
    }

    public boolean offerLast(E e) {
        if (isFull()) {
            return false;
        }
        tail = (tail - 1 + capacity) % capacity;
        array[tail] = e;
        return true;
    }

    public E pollFirst() {
        if (isEmpty()) {
            return null;
        }
        head = (head - 1 + capacity) % capacity;
        E value = array[head];
        array[head] = null;
        return value;
    }

    public E pollLast() {
        if (isEmpty()) {
            return null;
        }
        E value = array[tail];
        array[tail] = null;
        tail = (tail + 1) % capacity;
        return value;
    }

    public E peekFirst() {
        return array[(head - 1 + capacity) % capacity];
    }

    public E peekLast() {
        return array[tail];
    }

    public boolean isEmpty() {
        return head == tail;
    }

    public boolean isFull() {
        return (tail - 1 + capacity) % capacity == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[(p - 1 + capacity) % capacity];
                p = (p - 1 + capacity) % capacity;
                return value;
            }
        };
    }
}
